package process;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProcessDownload extends Action {

    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        Logger l = LoggerFactory.getLogger( ProcessDownload.class ); 
        
        String param = (String) request.getQueryString();
        URLDecoder ud=new URLDecoder();
        String filePath =   ud.decode(param.split( "=" )[1]) ;
        String fileName = filePath.split( "\\\\" )[ (filePath.split("\\\\").length)-1];
        l.debug( " downloading filename : " + fileName + " from " + filePath );
        
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        
       try 
        {
            FileInputStream in = 
                new FileInputStream(new File(filePath));
            

            ServletOutputStream out = response.getOutputStream();
             
            byte[] outputByte = new byte[4096];
            while(in.read(outputByte, 0, 4096) != -1)
            {
                out.write(outputByte, 0, 4096);
            }
            in.close();
            out.flush();
            out.close();

        }catch(Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
